package com.wu.leetcode.leetcode840;

/**
 * Leetcode840-矩阵中的幻方
 *
 * @author lynn
 * @date 2020/10/31 - 20:06
 */
public class Solution {
    public int numMagicSquaresInside(int[][] grid) {
        int r = grid.length, c = grid[0].length;
        int ans = 0;
        for (int i = 0; i < r - 2; ++i) {
            for (int j = 0; j < c - 2; ++j) {
                if (grid[i + 1][j + 1] != 5) {
                    continue;  // optional skip
                }
                if (magic(grid[i][j], grid[i][j + 1], grid[i][j + 2],
                        grid[i + 1][j], grid[i + 1][j + 1], grid[i + 1][j + 2],
                        grid[i + 2][j], grid[i + 2][j + 1], grid[i + 2][j + 2])) {
                    ans++;
                }
            }
        }

        return ans;
    }

    public boolean magic(int... vals) {
        int[] count = new int[16];
        for (int v : vals) {
            count[v]++;
        }
        for (int v = 1; v <= 9; ++v) {
            if (count[v] != 1) {
                return false;
            }
        }

        return (vals[0] + vals[1] + vals[2] == 15 &&
                vals[3] + vals[4] + vals[5] == 15 &&
                vals[6] + vals[7] + vals[8] == 15 &&
                vals[0] + vals[3] + vals[6] == 15 &&
                vals[1] + vals[4] + vals[7] == 15 &&
                vals[2] + vals[5] + vals[8] == 15 &&
                vals[0] + vals[4] + vals[8] == 15 &&
                vals[2] + vals[4] + vals[6] == 15);
    }
}
